package 网络编程.udp;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName UDPSenderB.java
 * @Description 发送端B
 * @createTime 2023年05月04日 08:48:00
 */
public class UDPSenderB {
    public static void main(String[] args) throws IOException {

        //创建DatagramSocket 对象，准备在9998端口接收数据
        DatagramSocket socket = new DatagramSocket(9998);

        //将需要发送的数据，封装到DatagramPacket对象
        byte[] data = "hello，明天吃火锅~".getBytes();

        //说明：封装的 DatagramPacket对象 data 内容字节数组 ，data.length ,主机（Ip），端口号
        DatagramPacket packet =
                new DatagramPacket(data, data.length, InetAddress.getByName("192.168.17.1"), 9999);
        socket.send(packet);

        //=====接收从A端回复的数据

        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        System.out.println("发送端B,等待回复数据....");
        socket.receive(packet);

        int length = packet.getLength();
        data = packet.getData();
        String s = new String(data,0,length);
        System.out.println(s);

        socket.close();
        System.out.println("B端退出");
    }
}
